<template>
  <div>
    <el-upload
      action="#"
      :http-request="httpRequest"
      list-type="picture-card"
      :before-upload="beforeUpload"
      :file-list="fileList"
      :class="{disabled: fileList.length === 1}"
      :on-remove="onRemove"
      :on-preview="onPreview"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-dialog
      title="图片预览"
      :visible.sync="showDialog"
      append-to-body
    >
      <img :src="imgUrl" alt=""></el-dialog>

  </div>
</template>

<script>
import { uploadImage } from '@/api/bjd/com'
export default {
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      fileList: [],
      showDialog: false,
      imgUrl: ''
    }
  },
  watch: {
    value: {
      handler() {
        this.fileList = this.value ? [{ url: 'http://124.223.14.236:8881' + this.value }] : []
      }
    }
  },
  methods: {
    // onUploadSuccess(val) {
    //   console.log(val)
    // },
    // 上传文件的文件信息
    async httpRequest({ file }) {
      // console.log(file)
      const fd = new FormData()
      fd.append('file', file)
      const res = await uploadImage(fd)
      console.log(res)
      this.$emit('input', res.data.url)
      // this.formData.advimgsrc = res.savePath
      this.fileList = [{ url: 'http://124.223.14.236:8881' + res.data.url }]
    },
    // 上传之前的钩子
    beforeUpload(file) {
      // console.log(file)
      if ((file.size / 1024 / 1024) > 2) {
        this.$message.error('图片大小不能超过2M')
        return false
      }
      const typeList = ['image/jpeg', 'image/png', 'image/jpg', 'image/gif']
      if (!typeList.includes(file.type)) {
        this.$message.warning('图片格式不正确')
        return false
      }
      return true
    },
    // 图片移除
    onRemove() {
      this.fileList = []
      this.$emit('input', '')
    },
    // 点击文件列表中已上传的文件时的钩子，可以用于预览
    onPreview(val) {
      console.log(val)
      this.imgUrl = val.url
      this.showDialog = true
    }
  }
}
</script>

<style lang="scss" scoped>
.disabled{
  ::v-deep .el-upload--picture-card{
    display: none;
  }
}
</style>
